from sqlalchemy import String, BigInteger, ForeignKey, UniqueConstraint, Boolean
from sqlalchemy.orm import Mapped, mapped_column, relationship

from rosa.love_is_blue import OrmBaseModel
from rosa.love_is_blue.backend.sqlalchemy.sqlalchemy_tools import ModelBase


class UserRole(ModelBase):
    """
    用户角色关联表
    """
    __tablename__ = "user_role"

    id: Mapped[int] = mapped_column("id", BigInteger, primary_key=True, comment="用户角色关联表id")
    # 添加级联删除
    user_id: Mapped[int] = mapped_column("user_id", BigInteger, ForeignKey("user.id", ondelete="CASCADE"), comment="用户id")
    role_id: Mapped[int] = mapped_column("role_id", BigInteger, ForeignKey("role.id", ondelete="CASCADE"), comment="角色id")

    # 联合唯一索引
    __table_args__ = (
        UniqueConstraint("user_id", "role_id", name="user_id_role_id"),
    )


class Role(OrmBaseModel):
    """
    角色表
    """
    __tablename__ = "role"

    name: Mapped[str] = mapped_column("name", String(128), comment="角色名称", unique=True)

    users = relationship("User", secondary="user_role", back_populates="roles")


class User(OrmBaseModel):
    """
    用户表
    """
    __tablename__ = "user"

    username: Mapped[str] = mapped_column("username", String(128), comment="用户登录名", unique=True)
    name: Mapped[str] = mapped_column("name", String(128), default="name", comment="用户展示名称，可以修改")
    superuser: Mapped[bool] = mapped_column("superuser", Boolean, default=False, comment="是否是超级管理员")

    roles = relationship("Role", secondary="user_role", back_populates="users")
